﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using QxFramework.Core;
public class Interact : ItemFunc
{
    public float InteractRadius = 2f;
    Item collectedItem;
    string effectName;
    public override void KeyDownPreference()
    {
        effectName = EffectsManager.Instance.Open("ScanCircle", this.transform.position, "ScanCircle_" + ThisItem.ItemFieldSetting.ItemName, 
            new System.Tuple<string, float>(ThisItem.ItemFieldSetting.ItemName,InteractRadius)).name;
    }

    public override void KeyOnInvoke()
    {
        base.KeyOnInvoke();
        var list =new List<Interaction>(Object.FindObjectsOfType<Interaction>());
        list.RemoveAll(s => s.enabled == false||Vector2.Distance(s.transform.position,this.transform.position)>InteractRadius);

        list.Sort((Interaction a, Interaction b) =>
        {
            var v = Vector2.Distance(a.transform.position, this.transform.position) - Vector2.Distance(b.transform.position, this.transform.position);
            //      return Vector2.Distance(a.transform.position, this.transform.position) < Vector2.Distance(b.transform.position, this.transform.position);
            if (v < 0f) return -1;
            else if (v > 0) return 1;
            else return 0;
        });
        if (list.Count>0)
        {
            collectedItem = list[0].GetComponentInParent<Item>();
            list[0].OnSelected();
        }
        else
        {
            collectedItem = null;
        }
     //   Debug.Log(collectedItem);

    }

    public override void KeyOnPreference()
    {
    //    throw new System.NotImplementedException();
    }

    public override void KeyUpInvoke()
    {
        base.KeyUpInvoke();
        if (collectedItem != null)
        {
            collectedItem.GetComponentInChildren<Interaction>().Invoke(this.gameObject.GetComponent<CombinableItem>().ItemFieldSetting as CombinableItemField);
        }
        Debug.Log("KeyUpInvoke");
    }
    public override void KeyUpPreference()
    {
        if (effectName != default)
        {
        EffectsManager.Instance.CloseEffect(effectName);

        }
        effectName = default;
    }
    public override void OnDestory()
    {
        base.OnDestory();
        if(effectName!=default)
        EffectsManager.Instance.CloseEffect(effectName);
        effectName = default;
    }
    private void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere
        (this.transform.position, InteractRadius);
    }
}
